package com.CMUBiS.PageServlets;
import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import com.CMUBiS.Data.Error;
import com.CMUBiS.Data.Footer;
import com.CMUBiS.Data.GlobalVars;
import com.CMUBiS.Data.Header;
import com.CMUBiS.PageControllers.*;
import com.CMUBiS.util.Item;
import com.CMUBiS.util.StopWatch;

/**
 * This servlet is a blank example
 * 
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 * @version 0.1
 * @since 0.1
 * @date 04/05/2011
 * 
 */
@WebServlet(name="ViewItemServlet", urlPatterns="/viewitem")
public class ViewItemServlet extends HttpServlet {
	
	
	
	private static final long serialVersionUID = 6475041456628458743L;
	private static final String EMPTY = "";
	private static final String title = "View Item";
	
	/**
	 * Get the page, calls the page to be made
	 * We used to check the parameters in here, but I moved it to a controller object to keep the logic away from the layout
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		makePage(request, response, Boolean.FALSE);
	}
	
	/**
	 * Get the page, we can just pass this to doPost since the client generator will be posting userIDs and authTokens all the time
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		makePage(request, response, Boolean.TRUE);
	}
	
	/**
	 * This method starts the page timer, writes the header, creates the HTML for the page, writes the stats, and the footer
	 * 
	 * @param request The incoming user request
	 * @param response  The out going user response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void makePage(HttpServletRequest request, HttpServletResponse response, Boolean isGet)  throws ServletException, IOException {
		if(request !=null && response != null){
			// Do the timer if we are collecting stats
			StopWatch timer;
			if(GlobalVars.collectStats){
				timer = new StopWatch();
				timer.start();
			}
			
			// Create a new page controller for this page, it will get and process the data
			ViewItemController vars = new ViewItemController();
			vars.checkInputs(request);
			
			// If there are no errors we can insert the bid
			if(!isGet && vars.getErrors().size() == 0){
				if(vars.submitBid()){
					timer.stop();
					response.sendRedirect(vars.getRedirectURL());
				}
			}
			
			// We are using PrintWriter to be friendly to the international community. PrintWrite auto-converts coding
			PrintWriter out = response.getWriter();
	
			// Set the return type
			response.setContentType("text/html");
			
			// Write the page header
			Header.writeHeader(out, title, vars.getUserIDString(), vars.getAuthTokenString());
			
			// If the output is to be suppressed then we'll redirect the output
			if(vars.getSuppressOutput())
				out = new PrintWriter(GlobalVars.blackHole);
			
			// Do HTML4 or 5 depending on the global variables
			if(GlobalVars.isHTML4)
				createHTML4(out, vars, isGet);
			else
				createHTML5(out, vars, isGet);
			
			// Redirect the output to start writing the the user again in case we were putting it in the black hole
			out = response.getWriter();
			
			/*
			 * Output any errors. These don't need to be too pretty since we hope there isn't any!
			 * We put them here to help with debug and info, the page above should show pretty ones for users
			 */
			if(GlobalVars.printAllErrors){
				out.println("<BR />Errors: " + vars.getErrors().size());
				for(Error error: vars.getErrors())
					out.println("<BR />" + error.getErrorNumber() + " " +error.toString());
			}
			
			/*
			 * Process the page time
			 */
			if(GlobalVars.collectStats){
				timer.stop();
				vars.setTotalTime(timer.getTimeTaken());
				GlobalVars.addStats(request, out, vars);
			}
			
			// Write the page footer
			Footer.writeFooter(out);
		}
	}
	
	/**
	 * Creates the HTML4 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML4(PrintWriter out, ViewItemController vars, Boolean isGet){
		if(out != null && vars != null)
		try{
			// Get the data needed to display the page
			vars.getHTML4Data();
			vars.processHTML4();
			
			// Make sure there is really an item to display
			Item item = vars.getItem();
				if(item != null){
				
				/*
				 * Print out the items basic information
				 */
				// Print out the thumbnail
				out.println(vars.getThumbnailURL());
				
				// Print out the items current price details
				
				out.println(item.getName() + "<br />");
				out.println("Item condition: <br />");
				out.println("Bidding Ends: " + item.getEndDate() + "<br />");
				out.println("Bidding History: " + item.getNoOfBids() + "<br />");
				out.println("Current Price: " + item.getCurrentBid() + "<br />");
				
				/*
				 * Print the bidding and buy now forms
				 */
				// If the auction is on going we can allow the user to bid
				if(!vars.getIsOld()){
					out.println(vars.reserveMet());
					
					// Print the form to allow bidding
					out.println("<form name=\"bid\" action=\"viewitem\" method=\"POST\">");
					
					out.println("<input type=\"hidden\" name=\"userID\" value=\"" + vars.getUserIDString() + "\">");
					out.println("<input type=\"hidden\" name=\"authToken\" value=\"" + vars.getAuthTokenString() + "\">");
					out.println("<input type=\"hidden\" name=\"itemID\" value=\"" + item.getID() + "\">");
					
					out.println("Quantity: <input type=\"text\" name=\"quantity\" size=\"2\" maxlength=\"2\" value=\"" + vars.getQuantity()+ "\"> (" + item.getQuantity() + " available) <br />");
					out.println("Your Bid: <input type=\"text\" name=\"bid\" size=\"10\" maxlength=\"10\" value=\"" + vars.getBid() + "\"> (Enter more than $" + item.getCurrentBid() + ") <br />");
					out.println("Your Maximum Bid: <input type=\"text\" name=\"maxBid\" size=\"10\" maxlength=\"10\" value=\"" + vars.getMaxBid() + "\"> (Enter more than $" + item.getCurrentBid() + ") <br />");
					out.println("<input type=\"submit\" value=\"Bid\">");
					out.println("</form><br />");
					
					// If the item has a buy now price we can buy it now
					if(vars.getCanBuyNow()){
						out.println("<form name=\"buyNow\" action=\"buyitem\" method=\"POST\">");
						
						out.println("<input type=\"hidden\" name=\"userID\" value=\"" + vars.getUserIDString() + "\">");
						out.println("<input type=\"hidden\" name=\"authToken\" value=\"" + vars.getAuthTokenString() + "\">");
						out.println("<input type=\"hidden\" name=\"itemID\" value=\"" + item.getID() + "\">");
						
						out.println(item.getBuyNowPrice() + " <input type=\"submit\" value=\"Buy Now\">");
						out.println("</form>");
					}
				}
				// If this was an old item
				else{
					out.println("The bidding on this item has finished.<BR />");
					out.println("Sale Price: " + item.getMaxBid() + "<BR />");
				}
				
				/*
				 * Print the items name and larger description
				 */
				out.println(item.getName() + "<BR />");
				out.println(item.getDescription() + "<BR />");
				
				/*
				 * Print out the items pictures 
				 */
				String[] imageURLs = vars.getImageURLs();
				if(imageURLs != null && imageURLs.length>0){
					for(int i=0; i<imageURLs.length; i++)
						out.println(imageURLs[i] + "<BR />");
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Creates the HTML5 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML5(PrintWriter out, ViewItemController vars, Boolean isGet){
		if(out != null && vars != null)
		try{
			// Get the data needed to display the page
			vars.getHTML5Data();
			vars.processHTML5();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
